// request.js
import config from './config'


// 封装的请求函数
export function request(url, method = 'GET', data = {}) {
  let fullUrl = config.BASE_URL + url

  return new Promise((resolve, reject) => {
    wx.request({
      url: fullUrl,
      method: method,
      data: data,
      header: {
        'content-type': 'application/json',
        'Authorization': wx.getStorageSync('token'),
        'x-refresh-token': wx.getStorageSync('x-refresh-token'),
      },
      success: (res) => {
        
        if (res.statusCode === 200) {
          try {
            // 触发了双Token刷新机制，返回的新Token存到storage里面
            const headers = res.header || res.headers; // 兼容不同基础库版本
            var newToken = headers['new-access-token']
            var newExpire = headers['new-access-expires-at']

            var refreshToken = headers['x-refresh-token']
            if(typeof  newToken!=='undefined'){
              wx.setStorageSync('token', newToken)
              wx.setStorageSync('expire', newExpire)
            }

            if (typeof  refreshToken!=='undefined'){
              wx.setStorageSync('x-refresh-token', refreshToken)
            }
          } catch (e) {
            // 无事发生
          } finally {
            // 无论有没有都要返回给调用者
            resolve(res.data)
          }
        }
      },
      fail: (err) => {
        reject(err.errMsg || '网络请求失败')
      }
    })
  })
}